import { createRouter, createWebHistory } from 'vue-router'
import { useUserAuthStore } from '@/stores/userAuth'

// 路由懒加载优化
const routes = [
  {
    path: '/',
    component: () => import(/* webpackChunkName: "main" */ '../vueHome/MainView.vue'),
    children: [
      {
        path: '',
        name: 'Home',
        component: () => import(/* webpackChunkName: "home" */ '../components/MainContent.vue')
      },
      {
        path: 'messages',
        name: 'LegalAidMessages',
        component: () => import(/* webpackChunkName: "messages" */ '../components/LegalAidMessages.vue')
      },
      {
        path: 'lawyer-team',
        name: 'LawyerTeam',
        component: () => import(/* webpackChunkName: "lawyer" */ '../views/LawyerTeam.vue')
      },
      {
        path: 'legal-resource',
        name: 'LegalResource',
        component: () => import(/* webpackChunkName: "resource" */ '../views/LegalResource.vue')
      },
      {
        path: 'legal-news',
        name: 'LegalNews',
        component: () => import(/* webpackChunkName: "news" */ '../views/LegalNews.vue')
      },
      {
        path: 'contact-us',
        name: 'ContactUs',
        component: () => import(/* webpackChunkName: "contact" */ '../views/ContactUs.vue')
      },
      {
        path: 'case',
        name: 'CaseManage',
        component: () => import('../views/CaseManage.vue'),
        meta: {
          title: '案件管理',
          permission: 'case:manage',
          requiresAuth: true
        }
      },
      {
        path: 'case-apply',
        name: 'CaseApply',
        component: () => import('../views/CaseApply.vue'),
        meta: {
          title: '申请案件',
          requiresAuth: true
        }
      },
      {
        path: '/case-detail/:id',
        name: 'CaseDetail',
        component: () => import('../views/CaseDetail.vue')
      },
      {
        path: '/case-edit/:id',
        name: 'CaseEdit',
        component: () => import('../views/CaseEdit.vue')
      },
      {
        path: 'test-auth',
        name: 'TestAuth',
        component: () => import(/* webpackChunkName: "test" */ '../views/TestAuth.vue'),
        meta: {
          title: '认证功能测试',
          requiresAuth: false // 测试页面不需要登录
        }
      },
      {
        path: 'user',
        name: 'UserView',
        component: () => import('../views/UserView.vue')
      },
      {
        path: 'ai-qa',
        name: 'AiQa',
        component: () => import('../views/AiQa.vue')
      },
      {
        path: 'test-ai',
        name: 'TestAI',
        component: () => import('../views/TestAI.vue'),
        meta: {
          title: 'AI助手测试',
          requiresAuth: false
        }
      },
    ]
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "auth" */ '../components/Login.vue'),
    meta: {
      requiresAuth: false
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import(/* webpackChunkName: "error" */ '../views/NotFound.vue'),
    meta: {
      requiresAuth: false
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 滚动行为优化
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由加载进度条
let loadingBar = null

// 全局前置守卫：权限控制
router.beforeEach(async (to, from, next) => {
  // 显示加载进度条
  if (!loadingBar) {
    loadingBar = document.createElement('div')
    loadingBar.style.cssText = `
      position: fixed;
      top: 0;
      left: 0;
      width: 0%;
      height: 2px;
      background: linear-gradient(90deg, #409eff, #67c23a);
      z-index: 9999;
      transition: width 0.3s ease;
    `
    document.body.appendChild(loadingBar)
  }
  
  // 开始加载
  loadingBar.style.width = '30%'
  
  const userAuthStore = useUserAuthStore()
  const isLogin = userAuthStore.isLogin
  
  // 如果路由不需要认证，直接通过
  if (to.meta.requiresAuth === false) {
    loadingBar.style.width = '100%'
    setTimeout(() => {
      if (loadingBar && loadingBar.parentNode) {
        loadingBar.parentNode.removeChild(loadingBar)
        loadingBar = null
      }
    }, 300)
    next()
    return
  }
  
  // 检查是否需要登录
  if (!isLogin) {
    // 保存目标路由，登录后跳转
    if (to.path !== '/login') {
      loadingBar.style.width = '100%'
      setTimeout(() => {
        if (loadingBar && loadingBar.parentNode) {
          loadingBar.parentNode.removeChild(loadingBar)
          loadingBar = null
        }
      }, 300)
      next('/login')
    } else {
      loadingBar.style.width = '100%'
      setTimeout(() => {
        if (loadingBar && loadingBar.parentNode) {
          loadingBar.parentNode.removeChild(loadingBar)
          loadingBar = null
        }
      }, 300)
      next()
    }
    return
  }
  
  // 已登录用户访问登录页，跳转到首页
  if (to.path === '/login') {
    loadingBar.style.width = '100%'
    setTimeout(() => {
      if (loadingBar && loadingBar.parentNode) {
        loadingBar.parentNode.removeChild(loadingBar)
        loadingBar = null
      }
    }, 300)
    next('/')
    return
  }
  
  // 检查权限
  if (to.meta.permission) {
    if (userAuthStore.checkPermission(to.meta.permission)) {
      loadingBar.style.width = '100%'
      setTimeout(() => {
        if (loadingBar && loadingBar.parentNode) {
          loadingBar.parentNode.removeChild(loadingBar)
          loadingBar = null
        }
      }, 300)
      next()
    } else {
      // 权限不足，可以跳转到错误页面或首页
      console.warn('权限不足:', to.meta.permission)
      loadingBar.style.width = '100%'
      setTimeout(() => {
        if (loadingBar && loadingBar.parentNode) {
          loadingBar.parentNode.removeChild(loadingBar)
          loadingBar = null
        }
      }, 300)
      next('/')
    }
    return
  }
  
  // 其他情况正常通过
  loadingBar.style.width = '100%'
  setTimeout(() => {
    if (loadingBar && loadingBar.parentNode) {
      loadingBar.parentNode.removeChild(loadingBar)
      loadingBar = null
    }
  }, 300)
  next()
})

// 全局后置钩子：页面标题设置
router.afterEach((to) => {
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 法律援助平台`
  } else {
    document.title = '法律援助平台'
  }
  
  // 性能监控：记录路由切换时间
  if (import.meta.env.DEV) {
    console.log(`📄 路由切换到: ${to.path}`)
  }
})

export default router 